package com.szis.auth.oauth2.config;

import cn.dev33.satoken.oauth2.data.loader.SaOAuth2DataLoader;
import cn.dev33.satoken.oauth2.data.model.loader.SaClientModel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.szis.auth.oauth2.entity.Client;
import com.szis.auth.oauth2.service.IClientService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * client信息加载
 *
 * @author: yxl
 * 2025-07-17
 */

@Component
public class ClientDataLoaderImpl implements SaOAuth2DataLoader {

    @Resource
    private IClientService clientService;

    @Override
    public SaClientModel getClientModel(String clientId) {
        Client client = clientService.getOne(new LambdaQueryWrapper<Client>().eq(Client::getClientName, clientId));
        if(client != null){
            return new SaClientModel()
                    .setClientId(clientId)
                    .setClientSecret(client.getClientSecret())
                    .setAllowRedirectUris(List.of(client.getRedirectUri().split(",")))
                    .setContractScopes(List.of(client.getScope().split(",")))
                    .setAllowGrantTypes(List.of(client.getGrantType().split(",")))
                    .setAccessTokenTimeout(client.getAccessTokenValidity())
                    .setRefreshTokenTimeout(client.getRefreshTokenValidity());
        }
        return null;
    }

    @Override
    public String getOpenid(String clientId, Object loginId) {
        return SaOAuth2DataLoader.super.getOpenid(clientId, loginId);
    }

    @Override
    public String getUnionid(String subjectId, Object loginId) {
        return SaOAuth2DataLoader.super.getUnionid(subjectId, loginId);
    }
}
